﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSqlError>
#include <QDebug>
#include <QGraphicsDropShadowEffect>
#include <QVBoxLayout>
#include <QFrame>
#include <QApplication>
#include <QLabel>

/**
 * @brief MainWindow::MainWindow 构造函数
 * @param parent 父窗口
 */
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , passwordVisible(false)
{
    ui->setupUi(this);
    
    // 初始化数据库
    initDatabase();
    
    // 优化：设置全局字体
    QApplication::setFont(QFont("Microsoft YaHei", 12));
    
    // 修改：扩大白色区域（表单容器）的上下空间
    QFrame *formFrame = new QFrame(ui->centralwidget);
    formFrame->setObjectName("formFrame");
    // 调整位置和尺寸：向上扩展以容纳标题，增加上下空间
    formFrame->setGeometry(60, 40, 380, 300);
    formFrame->setFrameShape(QFrame::NoFrame);
    formFrame->setStyleSheet("QFrame#formFrame { background-color: rgba(255, 255, 255, 240); border-radius: 16px; }");
    
    // 为表单容器添加阴影效果
    QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect(this);
    shadow->setOffset(0, 4);       // 阴影偏移
    shadow->setBlurRadius(12);     // 模糊程度
    shadow->setColor(QColor(0, 0, 0, 30)); // 半透明黑色
    formFrame->setGraphicsEffect(shadow);
    
    //将表单容器移到最底层，确保所有控件都在它上面
    formFrame->lower();
    
    //在白色区域添加"用户登录"标签
    QLabel *titleLabel = new QLabel("用户登录", formFrame);
    titleLabel->setGeometry(0, 20, 380, 40); // 设置位置和大小，使其水平居中
    titleLabel->setAlignment(Qt::AlignCenter); // 文本居中
    
    // 设置字体样式
    QFont titleFont("Microsoft YaHei", 18, QFont::Bold);
    titleLabel->setFont(titleFont);
    
    // 设置文字颜色为蓝色，与白色背景形成对比
    titleLabel->setStyleSheet("color: #1976D2; background-color: transparent;");
    
    // 确保标题显示在白色区域上方
    titleLabel->raise();
    
    ui->usernameEdit->setStyleSheet(
        "QLineEdit {" \
        "    border: 1px solid #D8D8D8;" \
        "    border-radius: 14px;" \
        "    padding: 6px 12px;" \
        "    background-color: white;" \
        "    color: black;" \
        "}" \
        "QLineEdit:focus {" \
        "    border-color: #409EFF;" \
        "}"
    );
    
    ui->passwordEdit->setStyleSheet(
        "QLineEdit {" \
        "    border: 1px solid #D8D8D8;" \
        "    border-radius: 14px;" \
        "    padding: 6px 12px;" \
        "    background-color: white;" \
        "    color: black;" \
        "}" \
        "QLineEdit:focus {" \
        "    border-color: #409EFF;" \
        "}"
    );
    
    ui->togglePasswordBtn->setStyleSheet(
        "QPushButton {" \
        "    background-color: transparent;" \
        "    border: none;" \
        "    padding: 0 8px;" \
        "}" \
        "QPushButton:hover {" \
        "    background-color: #F5F5F5;" \
        "    border-radius: 8px;" \
        "}"
    );
    
    ui->loginBtn->setStyleSheet(
        "QPushButton {" \
        "    background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(25, 118, 210, 255), stop:1 rgba(65, 105, 225, 255));" \
        "    color: white;" \
        "    border: none;" \
        "    border-radius: 18px;" \
        "    padding: 8px 0;" \
        "    font-size: 16px;" \
        "}" \
        "QPushButton:hover {" \
        "    background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(45, 138, 230, 255), stop:1 rgba(85, 125, 245, 255));" \
        "}" \
        "QPushButton:pressed {" \
        "    background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(15, 108, 200, 255), stop:1 rgba(55, 95, 215, 255));" \
        "}"
    );
    
    ui->cancelBtn->setStyleSheet(
        "QPushButton {" \
        "    background-color: white;" \
        "    color: #666;" \
        "    border: 1px solid #D8D8D8;" \
        "    border-radius: 14px;" \
        "}" \
        "QPushButton:hover {" \
        "    border-color: #409EFF;" \
        "}"
    );
    
    ui->registerBtn->setStyleSheet(
        "QPushButton {" \
        "    background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(33, 150, 243, 255), stop:1 rgba(66, 165, 245, 255));" \
        "    color: white;" \
        "    border: none;" \
        "    border-radius: 14px;" \
        "}" \
        "QPushButton:hover {" \
        "    background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(53, 170, 255, 255), stop:1 rgba(86, 185, 255, 255));" \
        "}"
    );
    
    this->setStyleSheet(
        "MainWindow {" \
        "    background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(234, 246, 255, 255), stop:1 rgba(201, 230, 255, 255));" \
        "}"
    );
}

/**
 * @brief MainWindow::~MainWindow 析构函数
 */
MainWindow::~MainWindow()
{
    // 关闭数据库连接
    if (db.isOpen()) {
        db.close();
    }
    delete ui;
}

/**
 * @brief MainWindow::initDatabase 初始化SQLite数据库
 */
void MainWindow::initDatabase()
{
    // 添加SQLite数据库驱动
    db = QSqlDatabase::addDatabase("QSQLITE");
    
    // 设置数据库文件路径
    db.setDatabaseName("users.db");
    
    // 打开数据库
    if (!db.open()) {
        QMessageBox::critical(this, "数据库错误", "无法打开数据库: " + db.lastError().text());
        return;
    }
    
    // 创建用户表（如果不存在）
    QSqlQuery query;
    QString createTableQuery = "CREATE TABLE IF NOT EXISTS users (" \
                               "id INTEGER PRIMARY KEY AUTOINCREMENT, " \
                               "username TEXT NOT NULL UNIQUE, " \
                               "password TEXT NOT NULL)";
    
    if (!query.exec(createTableQuery)) {
        QMessageBox::critical(this, "数据库错误", "无法创建用户表: " + query.lastError().text());
    }
}

/**
 * @brief MainWindow::on_togglePasswordBtn_clicked 切换密码显示/隐藏
 */
void MainWindow::on_togglePasswordBtn_clicked()
{
    passwordVisible = !passwordVisible;
    
    if (passwordVisible) {
        ui->passwordEdit->setEchoMode(QLineEdit::Normal);
        ui->togglePasswordBtn->setIcon(QIcon(":/img/images/show.jpg"));
    } else {
        ui->passwordEdit->setEchoMode(QLineEdit::Password);
        ui->togglePasswordBtn->setIcon(QIcon(":/img/images/unshow.jpg"));
    }
}

/**
 * @brief MainWindow::on_loginBtn_clicked 登录按钮点击事件
 */
void MainWindow::on_loginBtn_clicked()
{
    QString username = ui->usernameEdit->text();
    QString password = ui->passwordEdit->text();
    
    // 验证输入
    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "登录失败", "用户名和密码不能为空");
        return;
    }
    
    // 检查凭据
    if (checkCredentials(username, password)) {
        QMessageBox::information(this, "登录成功", "欢迎回来，" + username + "!");
        // 这里可以添加登录成功后的操作
    } else {
        QMessageBox::warning(this, "登录失败", "用户名或密码错误");
    }
}

/**
 * @brief MainWindow::on_cancelBtn_clicked 取消按钮点击事件
 */
void MainWindow::on_cancelBtn_clicked()
{
    ui->usernameEdit->clear();
    ui->passwordEdit->clear();
    ui->usernameEdit->setFocus();
}

/**
 * @brief MainWindow::on_registerBtn_clicked 注册按钮点击事件
 */
void MainWindow::on_registerBtn_clicked()
{
    QString username = ui->usernameEdit->text();
    QString password = ui->passwordEdit->text();
    
    // 验证输入
    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "注册失败", "用户名和密码不能为空");
        return;
    }
    
    // 注册用户
    if (registerUser(username, password)) {
        QMessageBox::information(this, "注册成功", "账号注册成功，请登录");
    }
}

/**
 * @brief MainWindow::checkCredentials 检查用户凭据
 * @param username 用户名
 * @param password 密码
 * @return 验证成功返回true，否则返回false
 */
bool MainWindow::checkCredentials(const QString &username, const QString &password)
{
    QSqlQuery query;
    query.prepare("SELECT password FROM users WHERE username = ?");
    query.addBindValue(username);
    
    if (!query.exec()) {
        QMessageBox::critical(this, "数据库错误", "查询失败: " + query.lastError().text());
        return false;
    }
    
    if (query.next()) {
        QString storedPassword = query.value(0).toString();
        return (storedPassword == password);
    }
    
    return false;
}

/**
 * @brief MainWindow::registerUser 注册新用户
 * @param username 用户名
 * @param password 密码
 * @return 注册成功返回true，否则返回false
 */
bool MainWindow::registerUser(const QString &username, const QString &password)
{
    QSqlQuery query;
    query.prepare("INSERT INTO users (username, password) VALUES (?, ?)");
    query.addBindValue(username);
    query.addBindValue(password);
    
    if (!query.exec()) {
        QMessageBox::critical(this, "注册失败", "该用户名已被使用");
        return false;
    }
    
    return true;
}
